﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Arch.Aspects;
using Arch.Common.Reflection;
using Arch.Model;
using Arch.Common.Validation;

namespace Arch.Intercep.Interceptors
{
    public class ValidationInterceptor : IEntityInterceptor
    {
        public object Intercept(object entity, ActionTarget target)
        {
            if (entity != null)
            {
                var validateAttribute = entity.GetType().GetCustomAttributes(true).Where(a => a is Validate).FirstOrDefault() as Validate;

                if (validateAttribute != null)
                {
                    if (validateAttribute.ApplyValidation)
                    {
                        foreach (var include in validateAttribute.Includes)
                        {
                            Intercept(entity.get(include), target);
                        }
                    }
                }
                else
                {
                    entity.Validate();
                }
            }
            return entity;
        }
    }
}
